<?php
namespace Home\Controller;

use Think\Controller;
use Home\Org\Util\RedisClient;
use Home\Org\Util\Sqlserver;

/**
 * OA快递查询 异步方式
 * 
 * @author dem
 *        
 */
class ExpController extends Controller
{
    //触发异步任务
    private  $doClinetUrl = 'http://192.168.1.177:88/task/exp_clinet.php'; //将OA系统部署到linux服务器,并安装swoole 执行异步任务
    private $expApi = 'http://192.168.1.177:81/exp/?service=Express.query';
    
    protected $config = array(
        'app_type' => 'public'
    );

    /**
     * 查询快递 并更新数据状态
     */
    function query()
    {
        
        $code = I('code');
        $url = $this->expApi;
        $expCom = I('expCom','');
        $res =  json_decode($this->httpPost($url, array('expNo'=>$code,'expCom'=>$expCom,'isSimlple'=>0)),1);

        if(isset($res['ret'])&&$res['ret']=='200'){
            if(!$res['data']['start']){
                unset($res['data']['start']);
            }
            
            if(!$res['data']['end']){
                unset($res['data']['end']);
            }
            if($res['data']['expStatus']=='-1')
                $res['data']['expStatus'] = 3;
            
            if($res['data']['expStatus']!=2){

                //未签收状态  取最近一条物流信息
                if(isset($res['data']['msg'])&&$res['data']['msg']){
                    $startTime = strtotime($res['data']['msg'][0]['AcceptTime']);
                    $endTime =   strtotime($res['data']['msg'][count($res['data']['msg'])-1]['AcceptTime']);
                    $index = $endTime<$startTime?count($res['data']['msg'])-1:0;
                    if($index){
                        //顺序错误处理
                        $res['data']['msg'] = $this->msg_sort($res['data']['msg'], 'AcceptTime');
                    }
                    
                    $res['data']['start'] = $res['data']['msg'][0]['AcceptTime'];
                    $res['data']['startInfo'] = $res['data']['msg'][0]['AcceptStation'];
                    $res['data']['end'] = $res['data']['msg'][count($res['data']['msg'])-1]['AcceptTime'];
                    $res['data']['endInfo'] = $res['data']['msg'][count($res['data']['msg'])-1]['AcceptStation'];
                }
                   
               
            }
            
            if($res['data']['expNo']!=$code){
                M('Expresslog')->where("expNo='{$code}'")->save(array('expStatus'=>0));
            }else{
                unset($res['data']['msg']);
                M('Expresslog')->where("expNo='{$res['data']['expNo']}'")->save($res['data']);
            }
        }else{
            //服务器返回错误  
            M('Expresslog')->where("expNo='{$code}'")->save(array('expStatus'=>0));
        }
        echo "SUCCESS";
    }
    
    
    function msg_sort($arrays,$sort_key,$sort_order=SORT_ASC,$sort_type=SORT_NUMERIC ){
        if(is_array($arrays)){
            foreach ($arrays as $array){
                if(is_array($array)){
                    $key_arrays[] = $array[$sort_key];
                }else{
                    return false;
                }
            }
        }else{
            return false;
        }
        array_multisort($key_arrays,$sort_order,$sort_type,$arrays);
        return $arrays;
    }
    
    /**
     * 获取查询后的结果
     */
    function queryres()
    {
      
       $tag =  session('doquerytag');
       $count =  M('Expresslog')->where("tag ='{$tag}' ")->count();
       $list  =  M('Expresslog')->where("tag ='{$tag}' ")->select();
       $res=array('total'=>$count,'data'=>$list);
       $res =json_encode($res,JSON_UNESCAPED_UNICODE);
       echo $res;
    }


    /**
     * ajax定时检查剩余查询数量
     */
    public function checkQuerystatus(){
       $tag =  session('doquerytag');
       $count =  M('Expresslog')->where("tag ='{$tag}' and expStatus=-1 ")->count();
       echo $count;
    }
    
    /**
     * 保存需要查询的快递单号,并触发异步查询
     */
    function doexpressquery(){
        $result = array('code'=>0,'msg'=>'ok');
        $tag = uniqid(); //作为一次查询的唯一标识
        session('doquerytag',$tag);
        $data = I('codes');
        $data = explode("\n", $data);
        if(count($data)>1000){
             $result['code']=-1;
             $result['msg'] = '快递单数量不能大于1000';
             echo json_encode($result);
        }
        $sql = "replace  into think_expresslog (expno,tag,expCom) values";
        foreach ($data as $key=>$expno){
            $expInfo = explode("\t", $expno);
            $expno = '';
            $expCom = '';
            $expno = $expInfo[0];
            if(count($expInfo)>=2)
                $expCom = $expInfo[1];
           if($expno){
                 $par = "/[\x80-\xff]/";
                 $expno =  preg_replace($par,"",$expno); //过滤中文 */
                 $sql.= "("."'".$str = preg_replace('/[^0-9a-zA-Z]+/','',$expno)."',"."'{$tag}','{$expCom}'),";
           }
         
           
        }
        $sql = rtrim($sql,',');
        $save =   M('Expresslog')->execute($sql);
        
        if(!$save){
            $result['code']=-1;
            $result['msg'] = '数据保存失败了!';
        }
        
        $this->httpPost($this->doClinetUrl, null); //保存数据后 触发异步任务
        echo  json_encode($result);
       
    }
    
    
    

    private function httpPost($url ,$data,$timeoutMs=60 ){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, $timeoutMs);
    
        if (!empty($data)) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
    
        $rs = curl_exec($ch);
    
        curl_close($ch);
    
        return $rs;
    }

    
    /**
     * 导出查询结果
     */
    function export(){
        $tag =  session('doquerytag');
        $list =  M('Expresslog')->where("tag ='{$tag}' ")->select();
        
        Vendor('Excel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0)
        ->setCellValue('A1','快递单号')
        ->setCellValue('B1','快递公司')
        ->setCellValue('C1','快递状态')
        ->setCellValue('D1','揽件时间')
        ->setCellValue('E1','揽件信息')
        ->setCellValue('F1','签收时间')
        ->setCellValue('G1','签收信息');
        $i=2;             
        foreach ($list as $key=>$v){
            $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValueExplicit('A' . $i, $v['expNo'], \PHPExcel_Cell_DataType::TYPE_STRING)
            ->setCellValue("B".$i, $v['expCom'])
            ->setCellValue("C".$i, $v['expStatus']==2?"已签收":($v['expStatus']==1?"未签收":(($v['expStatus']==3?'异常':"无信息"))))
            ->setCellValueExplicit("D".$i,  $v['start'],\PHPExcel_Cell_DataType::TYPE_STRING)
            ->setCellValue("E".$i,  $v['startInfo'])
            ->setCellValueExplicit("F".$i, $v['end'],\PHPExcel_Cell_DataType::TYPE_STRING)
            ->setCellValue("G".$i,  $v['endInfo']);
            $i++;
        }
        
        $objPHPExcel->getActiveSheet()->setTitle('快递信息');
        $objPHPExcel->setActiveSheetIndex(0);
        $filename='Express'. date('YmdHis',time());
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        
        
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $filename . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter->save('php://output');
        
    }

    /**
     * 订阅快递模式,由快递服务推送已签收的快递信息
     */
    public function subscribe(){/* 
        import("@.ORG.Util.Sqlserver");
        $sqlser = new Sqlserver();
        $data = base64_decode(I('jsonData'));
        //$data = '{"expNo":"533967522390","expCom":"ZTO","expStatus":"2","start":"2017-03-19 15:22:36","startInfo":"[上海市] [宝山杨行]的联谊路240号已收件 电话:暂无","end":"2017-03-21 11:01:23","endInfo":"[郑州市] [郑州金水三部]的派件已签收 感谢使用中通快递,期待再次为您服务!","msg":[{"AcceptTime":"2017-03-19 15:22:36","AcceptStation":"[上海市] [宝山杨行]的联谊路240号已收件 电话:暂无"},{"AcceptTime":"2017-03-19 17:51:41","AcceptStation":"[上海市] 快件离开 [宝山杨行]已发往[郑州]"},{"AcceptTime":"2017-03-19 22:02:07","AcceptStation":"[上海市] 快件到达 [上海航空部]"},{"AcceptTime":"2017-03-19 22:04:29","AcceptStation":"[上海市] 快件离开 [上海航空部]已发往[郑州中转]"},{"AcceptTime":"2017-03-20 21:52:00","AcceptStation":"[郑州市] 快件离开 [郑州中转]已发往[郑州金水三部]"},{"AcceptTime":"2017-03-21 03:03:43","AcceptStation":"[郑州市] 快件到达 [郑州金水三部]"},{"AcceptTime":"2017-03-21 08:53:55","AcceptStation":"[郑州市] [郑州金水三部]的王世铭正在第1次派件 电话:18137149089 请保持电话畅通、耐心等待"},{"AcceptTime":"2017-03-21 11:01:23","AcceptStation":"[郑州市] [郑州金水三部]的派件已签收 感谢使用中通快递,期待再次为您服务!"}]}';
       
        if(!$data) return false;
        $sql = "EXECUTE  [dbo].[AX_CallbackUpdateSAP] '{$data}'";
        $res = $sqlser->query($sql);
        
     */
    ECHO 'OLD';
    EXIT;
    }
    

}